#include <regx52.h>

void timer0_init()
{
    // TIMER1  TIMER0
    // 0000     0000
    // 清除低4位
    // xxxx ????  => xxxx 0000   xxxx ???? & 1111 0000
    // 通过TMOD设置Timer的工作模式
    TMOD &= 0xF0;
    // xxxx xxx1  模式1
    TMOD |= 0x01;
    // 计时器启动，发令枪
    TR0 = 1;
    // 中断使能
    ET0 = 0;
    // 中断总开关
    EA = 1;
    // 为了和uart中断共存，启用一个中断优先级
    PT0 = 1;
}

unsigned int timer_seed = 0x1234;

unsigned int timer_rand()
{
    timer_seed = (timer_seed * 12345 + 67890) % 65535;
    return timer_seed;
}

unsigned int get_timer0_value()
{
    unsigned char high, low;
    do
    {
        // 确保 high和low的取值在一个中断周期内
        high = TH0;
        low = TL0;
    } while (high != TH0);
    // high 左移进行数据类型提升，组装成一个int
    return (high << 8) | low;
}

unsigned int update_timer_seed()
{
    timer_seed = get_timer0_value();
    return timer_seed;
}